<template>
  <!-- 工艺路线分配物料表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1300"
      draggable
      @close="closeDialog"
      :destroy-on-close="true"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-row>
            <el-col :span="8">
              <el-form-item label="工厂" prop="plantId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.plantId"
                  placeholder="请输入工厂"
                  clearable
                  @change="changePlant"
                  style="width: 230px"
                  filterable
                >
                  <el-option
                    v-for="item in plantList"
                    :key="item.id"
                    :label="item.organizationCode"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{ plantCode(formData.plantId) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作中心" prop="workCenterId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.workCenterId"
                  placeholder="请输入工作中心"
                  clearable
                  @change="changeWorkCenter"
                  style="width: 230px"
                  :disabled="formData.plantId === ''"
                  filterable
                >
                  <el-option
                    v-for="item in workCenters"
                    :key="item.id"
                    :label="`${item.workshopCode}-${item.workshopName}`"
                    :value="item.id"
                  />
                </el-select>

                <span v-else>{{
                  `${formData.workCenterCode}-${formData.workCenterName}`
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成品物料" prop="materialId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.materialId"
                  placeholder="请输入成品物料"
                  clearable
                  @change="changeFinishedMaterial"
                  style="width: 230px"
                  :disabled="formData.plantId === ''"
                  filterable
                >
                  <el-option
                    v-for="item in finishedMaterials"
                    :key="item.id"
                    :label="`${item.materialCode}-${item.materialName}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{
                  `${formData.materialCode}-${formData.materialName}`
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="工艺路线" prop="routingId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.routingId"
                  placeholder="请输入工艺路线"
                  clearable
                  @change="changeRouting"
                  style="width: 230px"
                  :disabled="formData.plantId === ''"
                  filterable
                >
                  <el-option
                    v-for="item in routings"
                    :key="item.id"
                    :label="`${item.routingCode}-${item.routingName}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{
                  `${formData.routingCode}-${formData.routingName}`
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="BOM" prop="bomId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.bomId"
                  placeholder="请选择BOM"
                  clearable
                  @change="changeBom"
                  style="width: 230px"
                  :disabled="formData.materialId === ''"
                  filterable
                >
                  <el-option
                    v-for="item in boms"
                    :key="item.id"
                    :label="`${item.bomCode}-${item.bomName}`"
                    :value="item.id"
                  />
                </el-select>
                <span v-else>{{
                  `${formData.bomCode}-${formData.bomName}`
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="版本编号" prop="versionNo">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.versionNo"
                  placeholder="请输入版本编号"
                  clearable
                />
                <span v-else>{{ formData.versionNo }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="图号" prop="figureNumber">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.figureNumber"
                  placeholder="请输入图号"
                  clearable
                  disabled
                />
                <span v-else>{{ formData.figureNumber }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="物料默认版本" prop="enabled">
                <el-radio-group
                  v-model="formData.isDefault"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
                <span v-else>{{ formData.isDefault == 1 ? "是" : "否" }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否启用" prop="enabled">
                <el-radio-group
                  v-model="formData.enabled"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
                <span v-else>{{
                  formData.enabled == 1 ? "启用" : "停用"
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                  type="textarea"
                  style="width: 1014px"
                />

                <text v-else>{{ formData.remarks }}</text>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button
              v-show="!props.isReadonly || !formData.id"
              type="success"
              plain
              @click="handleAdd"
            >
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable" style="max-height: 300px; overflow-y: auto">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column label="工序" props="processId" min-width="200">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.processId'"
                    :rules="rules.sonprocessId"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.processId"
                      placeholder="请选择工序"
                      clearable
                      @change="changeProcess($index, row.processId)"
                      :disabled="formData.routingId === ''"
                      filterable
                    >
                      <el-option
                        v-for="item in processList"
                        :key="item.id"
                        :label="`${item.processCode}-${item.processName}`"
                        :value="item.processId"
                      />
                    </el-select>
                    <span v-else>{{
                      `${row.processCode}-${row.processName}`
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="成品物料"
                props="productionMaterialId"
                min-width="250"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.productionMaterialId'"
                    :rules="rules.productionMaterialId"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.productionMaterialId"
                      placeholder="请选择成品物料"
                      clearable
                      class="wide-select"
                      @change="(e) => changeProductionMaterial($index, e)"
                      :disabled="formData.bomId === ''"
                      filterable
                    >
                      <el-option
                        v-for="item in materials"
                        :key="item.id"
                        :label="`${item.materialCode || ''}-${
                          item.materialName || ''
                        }`"
                        :value="item.materialId"
                      />
                    </el-select>
                    <span v-else>{{
                      `${row.productionMaterialCode || ""}-${
                        row.productionMaterialName || ""
                      }`
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="组件物料"
                props="materialId"
                min-width="250"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.materialId'"
                    :rules="rules.sonmaterialId"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.materialId"
                      placeholder="请选择组件物料"
                      clearable
                      class="wide-select"
                      @change="changeMaterial($index, row.materialId)"
                      :disabled="formData.bomId === ''"
                      filterable
                    >
                      <el-option
                        v-for="item in materials"
                        :key="item.id"
                        :label="`${item.materialCode}-${item.materialName}`"
                        :value="item.materialId"
                      />
                    </el-select>
                    <span v-else>{{
                      `${row.materialCode}-${row.materialName}`
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <!--<el-table-column
                label="单件定额"
                props="unitRating"
                min-width="120"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.unitRating'"
                    :rules="rules.unitRating"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.unitRating"
                      placeholder="请输入数量"
                      clearable
                    />
                    <span v-else>{{ row.unitRating }}</span>
                  </el-form-item>
                </template>
              </el-table-column>-->
              <el-table-column
                label="是否扣料"
                props="isReduceMaterials"
                min-width="120"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.isReduceMaterials'"
                    :rules="rules.sonisReduceMaterials"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.isReduceMaterials"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList('YesNo')"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>{{
                      useDictionary("YesNo", row.isReduceMaterials)
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="数量" props="matQuantity" min-width="120">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.matQuantity'"
                    :rules="rules.sonmatQuantity"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.matQuantity"
                      placeholder="请输入数量"
                      clearable
                    />
                    <span v-else>{{ row.matQuantity }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="数量单位"
                props="quantityUnit"
                min-width="120"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.quantityUnit'"
                    :rules="rules.sonquantityUnit"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.quantityUnit"
                      placeholder="请选择单位"
                      clearable
                      disabled
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'MeasurementUnit'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>

                    <span v-else>{{
                      useDictionary("MeasurementUnit", row.quantityUnit)
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注" props="remarks" min-width="150">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.remarks'"
                    :rules="rules.sonremarks"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.remarks"
                      placeholder="请输入备注"
                      clearable
                    />
                    <span v-else>{{ row.remarks }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="120"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESROUTINGALLOCATIONADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    formData.details = [
      {
        id: "",
        processId: "",
        processCode: "",
        processName: "",
        routingAllocationId: "",
        routingAllocationCode: "",
        materialId: "",
        materialCode: "",
        materialName: "",
        unitRating: "",
        matQuantity: "",
        isReduceMaterials: "1",
        quantityUnit: "",
        version: "",
        remarks: "",
        createTime: "",
        createdUserId: "",
        createdUserName: "",
        lastUpdateTime: "",
        lastUpdatedUserId: "",
        lastUpdatedUserName: "",
        enabled: "",
        deleted: "",
        productionMaterialId: "",
        productionMaterialCode: "",
        productionMaterialName: "",
      },
    ];
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  routingId: "",
  routingCode: "",
  routingName: "",
  versionNo: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  isDefault: 0,
  workCenterId: "",
  workCenterCode: "",
  workCenterName: "",
  bomId: "",
  bomCode: "",
  bomName: "",
  descriptionCode: "",
  figureNumber: "",
  version: "",
  enabled: 1,
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  remarks: "",
  details: [
    {
      id: "",
      processId: "",
      processCode: "",
      processName: "",
      routingAllocationId: "",
      routingAllocationCode: "",
      materialId: "",
      materialCode: "",
      materialName: "",
      unitRating: "",
      matQuantity: "",
      isReduceMaterials: "1",
      quantityUnit: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
      productionMaterialId: "",
      productionMaterialCode: "",
      productionMaterialName: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  routingId: [{ required: true, message: "请选择工艺路线", trigger: "change" }],
  versionNo: [{ required: true, message: "请输入版本编号", trigger: "change" }],
  materialId: [
    { required: true, message: "请选择成品物料", trigger: "change" },
  ],
  isDefault: [],
  workCenterId: [
    {
      message: "请选择工作中心",
      trigger: "change",
    },
  ],
  bomId: [{ required: true, message: "请选择BOM", trigger: "change" }],
  descriptionCode: [
    {
      required: true,
      message: "请输入物料号-工序-人数",
      trigger: "blur",
    },
  ],
  figureNumber: [],
  enabled: [],
  sonprocessId: [{ required: true, message: "请输入工序", trigger: "change" }],
  sonmaterialId: [
    { required: true, message: "请输入组件物料", trigger: "change" },
  ],
  productionMaterialId: [
    { required: true, message: "请输入成品物料", trigger: "change" },
  ],
  unitRating: [
    { required: true, message: "请输入单位定额", trigger: "blur" },
    {
      pattern: /^[0-9]+(\.[0-9]{1,6})?$/,
      message: "请输入数字",
      trigger: "blur",
    },
  ],
  sonisReduceMaterials: [
    { required: true, message: "请选择是否扣料", trigger: "change" },
  ],
  sonmatQuantity: [
    { required: true, message: "请输入数量", trigger: "blur" },
    {
      pattern: /^[0-9]+(\.[0-9]{1,6})?$/,
      message: "请输入数字",
      trigger: "blur",
    },
  ],
  sonquantityUnit: [
    { required: true, message: "请输入数量单位", trigger: "blur" },
  ],
  sonremarks: [{ message: "请输入备注", trigger: "change" }],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  processId: "",
  processCode: "",
  processName: "",
  routingAllocationId: "",
  routingAllocationCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  unitRating: "",
  matQuantity: "",
  isReduceMaterials: "1",
  quantityUnit: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  productionMaterialId: "",
  productionMaterialCode: "",
  productionMaterialName: "",
};

const details1 = {
  id: "",
  processId: "",
  processCode: "",
  processName: "",
  routingAllocationId: "",
  routingAllocationCode: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  unitRating: "",
  matQuantity: "",
  isReduceMaterials: "1",
  quantityUnit: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  productionMaterialId: "",
  productionMaterialCode: "",
  productionMaterialName: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getWorkCenter();
        getFinishedMaterials();
        getRoutings();
        getBoms();
        getMaterials();
        getProcessList();
        getdetails();
      }
    }
  }
);
/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.routingId = "";
  formData.routingCode = "";
  formData.routingName = "";
  formData.versionNo = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.isDefault = 0;
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.workCenterName = "";
  formData.bomId = "";
  formData.bomCode = "";
  formData.bomName = "";
  formData.descriptionCode = "";
  formData.figureNumber = "";
  formData.version = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.remarks = "";
}

const loading = ref(false);

const findDuplicates = (arr, prop) => {
  return Object.values(
    arr.reduce((acc, obj) => {
      const key = obj[prop];
      if (!acc[key]) acc[key] = [];
      acc[key].push(obj);
      return acc;
    }, {})
  ).filter((group) => group.length > 1);
};

function isError() {
  let result = 0;
  // 相同的工序，必须匹配相同的物料
  const { details } = formData;

  const dupProcessIds = findDuplicates(details, "processId");
  for (let i = 0; i < dupProcessIds.length; i++) {
    const dupPMaterialIds = findDuplicates(
      dupProcessIds[i],
      "productionMaterialId"
    );
    const dupMaterialIds = findDuplicates(dupProcessIds[i], "materialId");
    const length1 = dupPMaterialIds[0]?.length || 0;
    if (dupProcessIds[i].length !== length1) {
      return 1;
    } else {
      if (dupMaterialIds.length) {
        return 2;
      }
    }
  }
  return result;
}
/** 工艺路线分配物料保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // if (isError() === 1) {
      //   ElMessage.error("相同的工序只能匹配一种成品物料");
      //   return;
      // }
      if (isError() === 2) {
        ElMessage.error("相同的工序和成品物料，组件物料不能相同");
        return;
      }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/mesroutingallocation/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/mesroutingallocation/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  sondetails.data.forEach((item) => {
    item.isReduceMaterials = String(item.isReduceMaterials);
  });
  formData.details = sondetails.data;
}
onMounted(() => {
  getPlantList();
});
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const changePlant = (id: any) => {
  formData.plantId = id;
  formData.plantCode = plantCode(id);
  //工厂变更清除关联内容
  formData.workCenterId = "";
  formData.workCenterCode = "";
  formData.workCenterName = "";
  workCenters.value = [];
  getWorkCenter();
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  finishedMaterials.value = [];
  getFinishedMaterials();
  formData.routingId = "";
  formData.routingCode = "";
  formData.routingName = "";
  routings.value = [];
  formData.bomId = "";
  formData.bomCode = "";
  formData.bomName = "";
  formData.figureNumber = "";
  boms.value = [];
  formData.details[0] = details1;
  formData.details = [details1];
  materials.value = [];
  processList.value = [];
  changeProcess(0, "");
  changeMaterial(0, "");
  getRoutings();
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};

//工作中心
const workCenters = ref([]);
async function getWorkCenter() {
  if (formData.plantId) {
    await request({
      url: "mes/mesworkshop/getList",
      method: "post",
      data: { plantId: formData.plantId, enabled: 1 },
    }).then((res) => {
      workCenters.value = res.data;
    });
  }
}
const changeWorkCenter = (id: any) => {
  formData.workCenterId = id;
  workCenters.value.forEach((item) => {
    if (item.id === id) {
      formData.workCenterCode = item.workshopCode;
      formData.workCenterName = item.workshopName;
    }
  });
  if (!id) {
    formData.workCenterCode = "";
    formData.workCenterName = "";
  }
};

//成品物料
const finishedMaterials = ref([]);
async function getFinishedMaterials() {
  if (formData.plantId) {
    await request({
      url: "mdm/mdmmaterial/getProductionList",
      method: "post",
      // data: { plantId: formData.plantId, enabled: 1, materialType: 3 },
      data: { plantId: formData.plantId },
    }).then((res) => {
      finishedMaterials.value = res.data;
    });
  }
}
const changeFinishedMaterial = (id: any) => {
  formData.materialId = id;
  formData.figureNumber = "";
  finishedMaterials.value.forEach((item) => {
    if (item.id === id) {
      formData.materialCode = item.materialCode;
      formData.materialName = item.materialName;
      formData.figureNumber = item.figureNumber;
    }
  });
  formData.bomId = "";
  formData.bomCode = "";
  formData.bomName = "";
  formData.details[0] = details1;
  formData.details = [details1];
  materials.value = [];
  getBoms();
  changeMaterial(0, "");
  changeProductionMaterial(0, "");
};

//工艺路线
const routings = ref([]);
async function getRoutings() {
  if (formData.plantId) {
    await request({
      url: "mes/mesrouting/getAvailableList",
      method: "post",
      data: { plantId: formData.plantId },
    }).then((res) => {
      routings.value = res.data;
    });
  }
}
const changeRouting = (id: any) => {
  formData.routingId = id;
  routings.value.forEach((item) => {
    if (item.id === id) {
      formData.routingCode = item.routingCode;
      formData.routingName = item.routingName;
    }
  });
  formData.details[0] = details1;
  formData.details = [details1];
  processList.value = [];
  getProcessList();
  changeProcess(0, "");
};

//bom
const boms = ref([]);
async function getBoms() {
  if (formData.plantId) {
    await request({
      url: "mes/mesbom/getList",
      method: "post",
      data: {
        plantId: formData.plantId,
        // materialId: formData.materialId,
        enabled: 1,
      },
    }).then((res) => {
      boms.value = res.data;
    });
  }
}
const changeBom = (id: any) => {
  formData.bomId = id;
  boms.value.forEach((item) => {
    if (item.id === id) {
      formData.bomCode = item.bomCode;
      formData.bomName = item.bomName;
    }
  });
  materials.value = [];
  formData.details[0] = details1;
  formData.details = [details1];
  getMaterials();
  changeMaterial(0, "");
  changeProductionMaterial(0, "");
};

//工序
const processList = ref([]);
async function getProcessList() {
  if (formData.routingId) {
    await request({
      url: "mes/mesroutingprocess/getAvailableList",
      method: "post",
      data: {
        // plantId: formData.plantId,
        // workCenterId: formData.workCenterId,
        routingId: formData.routingId,
      },
    }).then((res) => {
      processList.value = res.data;
    });
  }
}
const changeProcess = (index: number, id: any) => {
  if (!id) {
    formData.details[index].processId = "";
    formData.details[index].processCode = "";
    formData.details[index].processName = "";
  }
  processList.value.forEach((item: any) => {
    //工序为空是清除信息
    if (item.processId == id) {
      formData.details[index].processId = item.processId;
      formData.details[index].processCode = item.processCode;
      formData.details[index].processName = item.processName;
    }
  });
};

//物料
const materials = ref([]);
async function getMaterials() {
  if (formData.bomId) {
    await request({
      url: "mes/mesbomdetail/getList",
      method: "post",
      data: { bomId: formData.bomId },
    }).then((res) => {
      materials.value = res.data;
      console.log(materials.value);
    });
  }
}
const changeMaterial = (index: number, id: any) => {
  if (!id) {
    formData.details[index].materialId = "";
    formData.details[index].materialCode = "";
    formData.details[index].materialName = "";
    formData.details[index].unitRating = "";
    formData.details[index].matQuantity = "";
    formData.details[index].isReduceMaterials = "";
    formData.details[index].quantityUnit = "";
  }
  materials.value.forEach((item: any) => {
    //物料为空是清除信息
    if (item.materialId == id) {
      formData.details[index].materialId = item.materialId;
      formData.details[index].materialCode = item.materialCode;
      formData.details[index].materialName = item.materialName;
      formData.details[index].unitRating = item.unitRating;
      formData.details[index].matQuantity = item.matQuantity;
      formData.details[index].isReduceMaterials = item.isReduceMaterials;
      formData.details[index].quantityUnit = item.quantityUnit;
    }
  });
};

const changeProductionMaterial = (index: number, id: any) => {
  if (!id) {
    formData.details[index].productionMaterialId = "";
    formData.details[index].productionMaterialCode = "";
    formData.details[index].productionMaterialName = "";
  }
  materials.value.forEach((item: any) => {
    //物料为空是清除信息
    const { materialId, materialCode, materialName } = item;
    if (materialId == id) {
      formData.details[index] = {
        ...formData.details[index],
        productionMaterialId: materialId,
        productionMaterialCode: materialCode,
        productionMaterialName: materialName,
      };
    }
  });
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
.wide-select {
  width: 220px; /* 设置宽度为300px */
}
</style>
